<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="用户名称" prop="userName">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入用户名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input
          v-model="queryParams.phone"
          placeholder="请输入用户手机号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="是否删除" prop="deleted">
        <el-select
          v-model="queryParams.deleted"
          placeholder="请选择是否删除"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
        <el-button
            type="danger"
            plain
            :disabled="isEmpty(checkedIds)"
            @click="handleDeleteBatch"
        >
          <Icon icon="ep:delete" class="mr-5px" /> 批量删除
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table
        row-key="id"
        v-loading="loading"
        :data="list"
        :stripe="true"
        :show-overflow-tooltip="true"
        @selection-change="handleRowCheckboxChange"
    >
    <el-table-column type="selection" width="55" />
      <el-table-column label="用户名称" align="center" prop="userName" />
      <el-table-column label="用户手机号" align="center" prop="phone" />
      <el-table-column label="用户地址" align="center" prop="address" />
      <el-table-column label="用户微信号" align="center" prop="wechatOpenid" />
      <el-table-column label="用户余额" align="center" prop="balance">
        <template #default="scope">
          <span :class="getBalanceClass(scope.row.balance)">{{ scope.row.balance }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="操作" align="center" min-width="400px">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
          >
            编辑
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
          >
            删除
          </el-button>
          <el-button
            link
            type="success"
            @click="openPetDialog(scope.row.id)"
          >
            关联的宠物
          </el-button>
          <el-button
            link
            type="warning"
            @click="openRechargeDialog(scope.row.id)"
          >
            充值
          </el-button>
          <el-button
            link
            type="info"
            @click="openConsumptionDialog(scope.row.id)"
          >
            消费
          </el-button>
          <el-button
            link
            type="info"
            @click="openRechargeRecordDialog(scope.row.id)"
          >
            充值记录
          </el-button>
          <el-button
            link
            type="primary"
            @click="openConsumeRecordDialog(scope.row.id)"
          >
            消费记录
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <UserForm ref="formRef" @success="getList" />

  <!-- 宠物弹窗：查看用户关联的宠物 -->
  <UserPetDialog ref="petDialogRef" />

  <!-- 充值弹窗：用户充值 -->
  <UserRechargeDialog ref="rechargeDialogRef" @success="getList" />

  <!-- 消费弹窗：用户消费 -->
  <UserConsumptionDialog ref="consumptionDialogRef" />

  <!-- 充值记录弹窗：查看用户充值记录 -->
  <UserRechargeRecordDialog ref="rechargeRecordDialogRef" />

  <!-- 消费记录弹窗：查看用户消费记录 -->
  <UserConsumeRecordDialog ref="consumeRecordDialogRef" />
</template>

<script setup lang="ts">
import {isEmpty} from '@/utils/is'
import {dateFormatter} from '@/utils/formatTime'
import download from '@/utils/download'
import {User, UserApi} from '@/api/javainfo/javainfo_user'
import UserForm from './UserForm.vue'
import UserPetDialog from './UserPetDialog.vue'
import UserRechargeDialog from './UserRechargeDialog.vue'
import UserConsumptionDialog from './UserConsumptionDialog.vue'
import UserRechargeRecordDialog from './UserRechargeRecordDialog.vue'
import UserConsumeRecordDialog from './UserConsumeRecordDialog.vue'

/** 用户 列表 */
defineOptions({ name: 'User' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<User[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  userName: undefined,
  phone: undefined,
  address: undefined,
  wechatOpenid: undefined,
  createTime: [],
  deleted: undefined,
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中
const currentRow = ref({}) // 当前行数据

/** 根据余额金额返回对应的样式类名 */
const getBalanceClass = (balance: number) => {
  if (balance > 10000) {
    return 'text-green-500 font-bold'
  } else if (balance >= 5000 && balance <= 10000) {
    return 'text-orange-500 font-bold'
  } else if (balance >= 0 && balance < 5000) {
    return 'text-blue-500 font-bold'
  } else {
    return 'text-red-500 font-bold'
  }
}

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await UserApi.getUserPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await UserApi.deleteUser(id)
    message.success(t('common.delSuccess'))
    currentRow.value = {}
    // 刷新列表
    await getList()
  } catch {}
}

/** 批量删除用户 */
const handleDeleteBatch = async () => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    await UserApi.deleteUserList(checkedIds.value);
    checkedIds.value = [];
    message.success(t('common.delSuccess'))
    await getList();
  } catch {}
}

const checkedIds = ref<number[]>([])
const handleRowCheckboxChange = (records: User[]) => {
  checkedIds.value = records.map((item) => item.id);
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await UserApi.exportUser(queryParams)
    download.excel(data, '用户.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 打开宠物弹窗 */
const petDialogRef = ref()
const openPetDialog = (id: number) => {
  petDialogRef.value.open(id)
}

/** 打开充值弹窗 */
const rechargeDialogRef = ref()
const openRechargeDialog = (id: number) => {
  rechargeDialogRef.value.open(id)
}

/** 打开消费弹窗 */
const consumptionDialogRef = ref()
const openConsumptionDialog = (id: number) => {
  consumptionDialogRef.value.open(id)
}

/** 打开充值记录弹窗 */
const rechargeRecordDialogRef = ref()
const openRechargeRecordDialog = (id: number) => {
  rechargeRecordDialogRef.value.open(id)
}

/** 打开消费记录弹窗 */
const consumeRecordDialogRef = ref()
const openConsumeRecordDialog = (id: number) => {
  consumeRecordDialogRef.value.open(id)
}

/** 初始化 **/
onMounted(() => {
  getList()
})
</script>

<style scoped>
.text-green-500 {
  color: #10b981;
}
.text-orange-500 {
  color: #f59e0b;
}
.text-blue-500 {
  color: #3b82f6;
}
.text-red-500 {
  color: #ef4444;
}
.font-bold {
  font-weight: bold;
}
</style>
